package com.zoke.daycarpool.ui;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.listener.SocializeListeners.UMAuthListener;
import com.umeng.socialize.exception.SocializeException;
import com.zoke.daycarpool.R;
import com.zoke.daycarpool.base.BaseUi;
import com.zoke.daycarpool.config.CarpoolConfig;
import com.zoke.daycarpool.config.CarpoolConfig.HttpCode;
import com.zoke.daycarpool.config.CarpoolParamStore;
import com.zoke.daycarpool.config.UrlBank;
import com.zoke.daycarpool.domain.Token;
import com.zoke.daycarpool.domain.UserBeen;
import com.zoke.daycarpool.domain.UserInstense;
import com.zoke.daycarpool.thirdapi.QQ;
import com.zoke.daycarpool.thirdapi.Sina;
import com.zoke.support.http.HttpStores;
import com.zoke.support.http.ZokeErro;
import com.zoke.support.http.ZokeParams;
import com.zoke.support.utils.LogUtil;
import com.zoke.support.view.ZokeToast;

/**
 * 登录
 * 
 * @author JackWu
 * @version
 * @date 2015-1-4
 * @_QQ_ 651319154
 */
public class Login extends BaseUi implements UMAuthListener {

	private UserInstense mUserManager;
	private RelativeLayout mQQContainer;
	private RelativeLayout mSinaContainer;
	private ImageView mLogoIv;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		mQQContainer = (RelativeLayout) findViewById(R.id.qq_container);
		mSinaContainer = (RelativeLayout) findViewById(R.id.weibo_container);
		mLogoIv = (ImageView) findViewById(R.id._login_logo);
		mEnableDoubleExit = true;
		mUserManager = UserInstense.getInstense(getApplicationContext());
		// // 判断登陆
		// handleLoginBtn();
		// Animation anim = AnimationUtils.loadAnimation(this,
		// R.anim.logo_scale);
		// anim.setAnimationListener(new MyAnimListen());
		// mLogoIv.startAnimation(anim);
	}

	// /** 控制登陆按钮显示隐藏 **/
	// private void handleLoginBtn() {
	// mQQContainer.setVisibility(!mUserManager.isLogin() ? View.VISIBLE
	// : View.INVISIBLE);
	// mSinaContainer.setVisibility(!mUserManager.isLogin() ? View.VISIBLE
	// : View.INVISIBLE);
	// }

	/** 检测登陆 **/
	private void checkLogin() {
		if (mUserManager.isLogin()) {
			// 已经登陆
			mUserManager.initUser();
			mIntent = new Intent(this, Main.class);
			startUI(mIntent);
			Login.this.finish();
			return;
		}
		// 没有登陆
	}

	/**
	 * 登陆qq
	 * 
	 * @param uid
	 **/
	private void fetchLoginQQ(String uid) {
		ZokeParams param = CarpoolParamStore.getDefaultParam(mHashCode);
		param.setUrl(UrlBank.doLogin);
		param.setOperator(HttpCode.QQ_LOGIN);
		param.put("channel", CarpoolConfig.LOGINTYPE_QQ);// 1代表qq
		param.put("openId", "" + uid);
		HttpStores.getInstense(getApplicationContext()).find(param);
	}

	/**
	 * @throws JSONException
	 **/
	private void handleResult(String result, String openId)
			throws JSONException {
		JSONObject jo = new JSONObject(result);
		String code = jo.optString("code");
		// 仅仅测试
		if ("10".equals(code)) {
			mIntent = new Intent(this, Completion.class);
			mIntent.putExtra(Completion.CHANELKEY, "" + 1);
			mIntent.putExtra(Completion.OPENIDKEY, "" + openId);
			startUI(mIntent);
			return;
		}
		if ("0".equals(code)) {
			// 非首次登陆 直接跳转到首页
			LogUtil.e("result==" + result);
			JSONObject joo = jo.getJSONObject("result");
			UserBeen userBeen = new UserBeen();
			userBeen.setIdentify(joo.optString("identity"));
			userBeen.setPhone(joo.optString("mobile"));
			userBeen.setUserName(joo.optString("name"));
			userBeen.setSex(joo.optString("sex"));
			userBeen.setPhoto(CarpoolConfig.HTTPURL + joo.optString("photo"));
			LogUtil.e("头像＝＝＋" + userBeen.getPhoto());
			userBeen.setUserId(jo.optString("sid"));
			// 更新Token
			Token.getTokener().updateToken(jo.optLong("token"));
			UserInstense.getInstense(getApplicationContext())
					.saveUser(userBeen);
			mIntent = new Intent(this, Main.class);
			startUI(mIntent);
			return;
		}
	}

	@Override
	public void onSuccess(ZokeParams out) {
		super.onSuccess(out);
		int operation = out.getOperator();
		String result = (String) out.getResult();
		if (operation == HttpCode.QQ_LOGIN) {
			//
			try {
				String openId = out.getStringValue("openId");
				handleResult(result, openId);
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return;
		}
	}

	@Override
	public void onFails(ZokeParams out) {
		super.onFails(out);
		ZokeErro erro = (ZokeErro) out.getResult();
		ZokeToast.show(getApplicationContext(), "" + erro.getErrorNo());
	}

	/** 登录qq **/
	public void onClickQQ(View view) {
		QQ.login(this, this);
	}

	/** 登录微博 **/
	public void onClickWeibo(View view) {
		Sina.loginSina(this, this);
	}

	@Override
	public void onCancel(SHARE_MEDIA arg0) {
		ZokeToast.show(getApplicationContext(), "取消授权");
		if (arg0 == SHARE_MEDIA.QQ) {
			//

			return;
		}
	}

	@Override
	public void onComplete(Bundle bundle, SHARE_MEDIA arg1) {
		if (arg1 == SHARE_MEDIA.QQ) {
			ZokeToast.show(getApplicationContext(), "授权成功");
			String uid = bundle.getString("uid");
			if (TextUtils.isEmpty(uid))
				return;

			fetchLoginQQ(uid);
			return;
		}
		//
		ZokeToast.show(getApplicationContext(), "授权成功");
		if (arg1 == SHARE_MEDIA.SINA) {
			return;
		}
	}

	@Override
	public void onError(SocializeException arg0, SHARE_MEDIA arg1) {
		// 授权失败
		ZokeToast.show(getApplicationContext(), "授权失败码" + arg0.getErrorCode());
	}

	@Override
	public void onStart(SHARE_MEDIA arg0) {
		// 开始授权
		ZokeToast.show(getApplicationContext(), "开始授权");
	}

}
